package com.ys.chatserver.http.file.d;

import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.httpfile.FileDownload;
import com.eva.framework.utils.LoggerFactory;
import com.ys.chatserver.http.file.u.CloudImageUploader;
import com.ys.chatserver.http.logic.filter.JwtHelper;
import com.ys.chatserver.http.logic.filter.JwtParam;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.MD5Util;
import org.slf4j.Logger;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.ys.chatserver.http.file.d.ShortVideoThumbDownloader.DEFAULT_THUMB_FILE_NAME;

/**
 * 群云盘图片下载
 *
 * @author Qxin
 */
public class CloudImageDownloader extends HttpServlet implements Servlet {

    private static final Logger logger = LoggerFactory.getLog();

    public CloudImageDownloader() {
    }

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        LoggerFactory.getLog().debug("[HTTP]下载云盘图片：你传过来的参数"
                + "file_name=" + req.getParameter("cloud_image_file_name")
                + ",enforceDawnload=" + req.getParameter("enforceDawnload")
                + ",one_pixel_transparent_if_no=" + req.getParameter("one_pixel_transparent_if_no")
                + ",[---- " + req.getContextPath() + "-" + req.getRequestURL() + "]");
        String groupId = req.getParameter("group_id");
        String fileName = req.getParameter("file_name");

        String queryString = req.getQueryString();
        String authToken;
        String time;
        String token = req.getParameter("token");
        if (Objects.isNull(token)) {
            token = req.getHeader("token");
            time = req.getHeader("time");
            authToken = req.getHeader("authToken");
        } else {
            time = req.getParameter("time");
            authToken = req.getParameter("authToken");
            queryString = queryString.substring(0, queryString.indexOf("&token"));
        }
        String path = String.format("/api/%s?%s", getServletName(), queryString);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("time", time);
        map.put("path", path);
        String s = MD5Util.MD5_32(JSONObject.toJSONString(map));
        if (authToken == null) {
            logger.info("------- authToken is null --------");
            return;
        }
        if (!authToken.equals(s)) {
            logger.info("------------ authToken not equal s ------------");
            return;
        }
        if (EmptyUtils.isNotEmpty(token)) { //token校验
            logger.info("------------ token not null ------------");
            JwtParam jwtParam = JwtHelper.parseJwt(token);
            String userUid = jwtParam.getUserId();
            try {
                logger.info("------------ token not null ------------");
                if (JwtHelper.tokenAuth(jwtParam)) {
                    logger.info("------------ token auth succ ------------");
                    processCloudDownload(res, userUid, groupId,
                            CloudImageUploader.getFileSaveDir(), fileName);
                }
            } catch (Exception e) {
                logger.info("------------ message:{} ------------", e.getMessage());
            }
        } else {
            logger.info("------------ token is null ------------");
        }

    }


    private void processCloudDownload(HttpServletResponse res
            , String userUid, String groupId, String file_dir
            , String fileName) throws IOException {
        try {
            if (!CommonUtils.isStringEmpty(fileName, true)
                    && !CommonUtils.isStringEmpty(groupId, true)) {

                String filePath = String.format(file_dir, groupId) + fileName;
                File file = new File(filePath);
                if (!file.exists()) {
                    file = new File(ShortVideoThumbDownloader.class.getResource(DEFAULT_THUMB_FILE_NAME).toURI());
                }
                FileDownload.download(res, file, fileName, FileDownload.CONTENT_TYPE_JPEG, false);

            } else {
                LoggerFactory.getLog().warn("[HTTP]对不起,用户【" + userUid + "】要下载的云盘图片(fileNameForServerDisk=" + fileName + ")不存在！");
            }
        } catch (Exception e) {
            LoggerFactory.getLog().warn("[HTTP]用户【" + userUid + "】的下载的云盘图片文件不存在，本次下次已提前结束(" + e.getMessage() + ")");
        }
    }


}
